package com.smugmugsoftware.airconcalc.advanced;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AdvancedChartFragment extends Fragment {

	// FROM CHART BUILDER
	private CategorySeries mSeries;
	private DefaultRenderer mRenderer;
	private String mDateFormat;
	private GraphicalView mChartView;

	private boolean threadKill;

	private static int[] COLORS = new int[] { Color.parseColor("#d21010"), Color.parseColor("#f5f211"), Color.parseColor("#4bce11"), Color.parseColor("#262ff1"),
		Color.parseColor("#f19d26"), Color.parseColor("#0dece4"), Color.parseColor("#c3c3c3"), Color.parseColor("#c707c0") };

	private SharedPreferences prefs;

	private static final int BUILDING_BY_ROOM = 1001;
	private static final int BUILDING_BY_SOURCE = 1002;
	private static final int ROOM_BY_SOURCE = 1003;

	private int chartType;
	private int chartSubtype;

	private MainActivityInterface activity;
	private View thisView;
	private Building thisBuilding;

	public AdvancedChartFragment() {}

	public AdvancedChartFragment(Building thisBuilding) {
		this.thisBuilding = thisBuilding;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
		this.chartType = BUILDING_BY_ROOM;
		this.chartSubtype = 0;

		setRetainInstance(true);

		if (savedInstanceState != null && savedInstanceState.getParcelable("SAVED_BUILDING") != null) {
			thisBuilding = savedInstanceState.getParcelable("SAVED_BUILDING");

			// FROM CHART BUILDER
			mSeries = (CategorySeries) savedInstanceState.getSerializable("current_series");
			mRenderer = (DefaultRenderer) savedInstanceState.getSerializable("current_renderer");
			mDateFormat = savedInstanceState.getString("date_format");

			chartType = savedInstanceState.getInt("CHART_TYPE");
			chartSubtype = savedInstanceState.getInt("CHART_SUBTYPE");
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			this.activity = (MainActivityInterface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		thisView = inflater.inflate(R.layout.advanced_chart_fragment, container, false);
		
		activity.displayInfoDialog(thisView.getContext(), InformationDialog.CHART_FIRST_RUN, "CHART_FIRST_RUN");
		
		return thisView;
	}

	@Override
	public void onResume() {
		super.onResume();

		populateChart();

		ImageView cancelButton = (ImageView) thisView.findViewById(R.id.cancel_button);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.closeChart();
			}
		});

		ImageView nextButton = (ImageView) thisView.findViewById(R.id.next_button);
		nextButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (chartType == BUILDING_BY_ROOM) {
					chartType = BUILDING_BY_SOURCE;
					populateChart();
				} else if (chartType == BUILDING_BY_SOURCE) {
					chartType = ROOM_BY_SOURCE;
					chartSubtype = 0;
					populateChart();
				} else if (chartType == ROOM_BY_SOURCE) {
					if (chartSubtype < thisBuilding.getRooms().size() - 1) {
						chartSubtype++;
						populateChart();
					} else if (chartSubtype >= thisBuilding.getRooms().size() - 1) {
						chartSubtype = 0;
						chartType = BUILDING_BY_ROOM;
						populateChart();
					}
				}
			}
		});

		ImageView previousButton = (ImageView) thisView.findViewById(R.id.previous_button);
		previousButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				if (chartType == BUILDING_BY_ROOM) {
					chartType = ROOM_BY_SOURCE;
					chartSubtype = thisBuilding.getRooms().size() - 1;
					populateChart();
				} else if (chartType == BUILDING_BY_SOURCE) {
					chartType = BUILDING_BY_ROOM;
					chartSubtype = 0;
					populateChart();
				} else if (chartType == ROOM_BY_SOURCE) {
					if (chartSubtype > 0) {
						chartSubtype--;
						populateChart();
					} else if (chartSubtype <= 0) {
						chartSubtype = 0;
						chartType = BUILDING_BY_SOURCE;
						populateChart();
					}
				}
			}
		});
	}

	private void drawChart() {
		
		if (mRenderer == null || mSeries == null || mRenderer.getSeriesRendererCount() != mSeries.getItemCount()) {
			return;
		}

		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
		mRenderer.setChartTitleTextSize(20);
		mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
		mRenderer.setStartAngle(90);
		mRenderer.setClickEnabled(true);
		mRenderer.setLabelsTextSize(16);
		mRenderer.setLegendTextSize(16);
		mRenderer.setZoomButtonsVisible(true);
		
		LinearLayout layout = (LinearLayout) thisView.findViewById(R.id.chart_window);
		mChartView = ChartFactory.getPieChartView(thisView.getContext(), mSeries, mRenderer);
		mChartView.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
				if (seriesSelection != null) {
					Toast.makeText(thisView.getContext(), mSeries.getCategory(seriesSelection.getPointIndex()) + ": " + (int) seriesSelection.getValue() + " BTU",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		layout.removeAllViews();
		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}

	private void populateChart() {
		threadKill = false;

		if (thisBuilding.getRooms().size() > 0) {
			mSeries = new CategorySeries("");
			mRenderer = new DefaultRenderer();

			new Thread(new Runnable() {

				public void run() {

					if (chartType == BUILDING_BY_ROOM) {
						setChartTitle("Building by Room");

						Room thisRoom = null;
						int colorCounter = 0;
						boolean countUp = true;
						for (int i = 0; i < thisBuilding.getRooms().size(); i++) {

							thisRoom = thisBuilding.getRooms().get(i);

							mSeries.add(thisRoom.getName(), thisRoom.getTotalRoomLoad(thisView.getContext()));
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[colorCounter]);
							mRenderer.addSeriesRenderer(renderer);

							if (countUp) {
								colorCounter++;
							} else if (!countUp) {
								colorCounter--;
							}

							if (colorCounter >= COLORS.length || (colorCounter == 0 && !countUp)) {
								if (countUp) {
									colorCounter = 3;
									countUp = false;
								} else if (!countUp) {
									colorCounter = 4;
									countUp = true;
								}
							}

							if (threadKill) {
								break;
							}

							renderChart();
						}

					} else if (chartType == BUILDING_BY_SOURCE) {

						double[] dataSeries = new double[] { 0, 0, 0, 0, 0, 0, 0 };
						double[] gotLoads = new double[7];

						setChartTitle("Building by Source");

						for (Room thisRoom : thisBuilding.getRooms()) {

							gotLoads = thisRoom.getRoomLoadBySource(thisView.getContext());

							for (int i = 0; i < dataSeries.length; i++) {
								dataSeries[i] = dataSeries[i] + gotLoads[i];
							}

							mSeries = new CategorySeries("");
							mRenderer = new DefaultRenderer();

							if (dataSeries[0] > 0) {
								mSeries.add("Walls", dataSeries[0]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[0]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[1] > 0) {
								mSeries.add("Windows", dataSeries[1]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[1]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[2] > 0) {
								mSeries.add("Doors", dataSeries[2]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[2]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[3] > 0) {
								mSeries.add("Ceiling", dataSeries[3]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[3]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[4] > 0) {
								mSeries.add("Floor", dataSeries[4]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[4]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[5] > 0) {
								mSeries.add("Sensible", dataSeries[5]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[5]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (dataSeries[6] > 0) {
								mSeries.add("Infiltration", dataSeries[6]);
								SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
								renderer.setColor(COLORS[6]);
								mRenderer.addSeriesRenderer(renderer);
							}

							if (threadKill) {
								break;
							}

							renderChart();
						}
					} else if (chartType == ROOM_BY_SOURCE) {
						setChartTitle(thisBuilding.getRooms().get(chartSubtype).getName() + " by Source");
						double[] dataSeries = thisBuilding.getRooms().get(chartSubtype).getRoomLoadBySource(thisView.getContext());

						if (dataSeries[0] > 0) {
							mSeries.add("Walls", dataSeries[0]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[0]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[1] > 0) {
							mSeries.add("Windows", dataSeries[1]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[1]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[2] > 0) {
							mSeries.add("Doors", dataSeries[2]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[2]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[3] > 0) {
							mSeries.add("Ceiling", dataSeries[3]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[3]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[4] > 0) {
							mSeries.add("Floor", dataSeries[4]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[4]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[5] > 0) {
							mSeries.add("Sensible", dataSeries[5]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[5]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (dataSeries[6] > 0) {
							mSeries.add("Infiltration", dataSeries[6]);
							SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
							renderer.setColor(COLORS[6]);
							mRenderer.addSeriesRenderer(renderer);
						}

						if (threadKill) {
							return;
						}

						renderChart();
					}

				}
			}).start();
		} else {
			((TextView) thisView.findViewById(R.id.chart_title_label)).setText("No rooms!\nPlease create at least one room.");
			((TextView) thisView.findViewById(R.id.chart_title_label)).setTextSize(14);
			((TextView) thisView.findViewById(R.id.chart_title_label)).setGravity(Gravity.CENTER_HORIZONTAL);
			((ImageView) thisView.findViewById(R.id.next_button)).setVisibility(View.GONE);
			((ImageView) thisView.findViewById(R.id.previous_button)).setVisibility(View.GONE);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putParcelable("SAVED_BUILDING", thisBuilding);

		outState.putSerializable("current_series", mSeries);
		outState.putSerializable("current_renderer", mRenderer);
		outState.putString("date_format", mDateFormat);
		outState.putInt("CHART_TYPE", chartType);
		outState.putInt("CHART_SUBTYPE", chartSubtype);		
	}

	protected void setChartTitle(final String s) {
		getActivity().runOnUiThread(new Runnable() {

			public void run() {

				((TextView) thisView.findViewById(R.id.chart_title_label)).setText(s);
			}
		});
	}

	protected void renderChart() {
		if (!threadKill) {
			if (activity != null) {
				getActivity().runOnUiThread(new Runnable() {

					public void run() {
						drawChart();	
					}
				});
			}
		}
	}
}
